﻿using System;
using System.Net;
using AdAggregator.Advertisement;
using AdAggregator.SearchData;
using AdAggregator.Website;

namespace AdAggregator.Parser
{
    public abstract class BaseParser<TSearchData, TAdvertisement> : IParser<TSearchData, TAdvertisement>
        where TSearchData : ISearchData
        where TAdvertisement : IAdvertisement
    {
        protected TSearchData SearchData;

        public abstract string Name { get; }

        public virtual IParseResult<TAdvertisement> Parse(TSearchData searchData, IAdvertisementSource<TAdvertisement> website)
        {
            SearchData = searchData;
            IParseResult<TAdvertisement> result = new ParseResult<TAdvertisement>();
            var uri = ComposeUri();
            var request = WebRequest.Create(uri) as HttpWebRequest;
            if (request != null)
            {
                var response = request.GetResponse() as HttpWebResponse;
                result = ParseResponse(response, website);
            }
            return result;
        }

        public virtual TAdvertisement ParseSingleAd(string adUrl, IAdvertisementSource<TAdvertisement> website)
        {
            return default(TAdvertisement);
        }

        protected abstract String ComposeUri();
        protected abstract IParseResult<TAdvertisement> ParseResponse(HttpWebResponse response, IAdvertisementSource<TAdvertisement> website);
    }
}